package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.pojo.Goods;
import com.zhentao.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/api/goods")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;

    @RequestMapping(value = "/list", method = {RequestMethod.GET, RequestMethod.POST})
    public IPage<Goods> listGoods(
            @RequestParam(defaultValue = "0") Integer sort,
            @RequestParam(defaultValue = "0") Integer sortType,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "30") Integer pageSize,
            @RequestParam(required = false) String keyword,
            @RequestParam(defaultValue = "0") Integer minPrice,
            @RequestParam(defaultValue = "100000") Integer maxPrice
    ) {
        Page<Goods> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Goods> wrapper = new QueryWrapper<>();
        if (keyword != null && !keyword.isEmpty()) {
            wrapper.like("goodsname", keyword);
        }
        wrapper.between("price", minPrice, maxPrice);
        if (Objects.equals(sort, 1)) {
            // 按价格排序
            if (Objects.equals(sortType, 0)) {
                wrapper.orderByAsc("price");
            } else {
                wrapper.orderByDesc("price");
            }
        } else {
            // 综合排序（默认按spuid降序）
            if (Objects.equals(sortType, 0)) {
                wrapper.orderByAsc("spuid");
            } else {
                wrapper.orderByDesc("spuid");
            }
        }
        return goodsService.page(page, wrapper);
    }
} 